import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";

import axios from "axios";

export const fetchHomeMultidataAction = createAsyncThunk('home/fetchHomeMultidata', async (dispatch, getState) => {
  const res = await axios.get('http://123.207.32.32:8000/home/multidata');
  // const banners = res.data.data.banner.list;
  // const recommends = res.data.data.recommend.list;
  // return {banners, recommends};
  return res.data

})

const homeSlice = createSlice({
  name: "home",
  initialState: {
    banners: [],
    recommends: []
  },
  reducers: {
    changeBanners: (state, action) => {
      state.banners = action.payload;
    },
    changeRecommends: (state, action) => {
      state.recommends = action.payload;
    }
  },
  // 监听异步操作 reducer
  // v2.0
 /*  extraReducers: {
    [fetchHomeMultidataAction.pending]: (state, action) => {
      console.log('请求中');
    },
    [fetchHomeMultidataAction.fulfilled]: (state, action) => {
      console.log('请求成功', action);
    },
    [fetchHomeMultidataAction.rejected]: (state, action) => {
      console.log('请求失败');
    }
  } */
  // new
  extraReducers:builder=>{
    builder.addCase('home/fetchHomeMultidata/fulfilled',(state, {payload})=>{
      console.log('请求中', payload);
      state.banners = payload.data.banner.list;
      state.recommends = payload.data.recommend.list;
    })
  }
  
});


export const { changeBanners, changeRecommends } = homeSlice.actions;
export default homeSlice.reducer;